package com.example.questionnaire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;
import com.example.questionnaire.dao.AnswererDao;
import com.example.questionnaire.dto.AnswererAddDto;
import com.example.questionnaire.entity.*;
import com.example.questionnaire.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("answererService")
public class AnswererServiceImpl extends ServiceImpl<AnswererDao, AnswererEntity> implements AnswererService {
    @Autowired
    UserAnswererService userAnswererService;
    @Autowired
    AnswererDao answererDao;
    @Autowired
    ResultService resultService;
    @Autowired
    AnswererService answererService;
    @Autowired
    AnswererTeamService answererTeamService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer current = Integer.parseInt(params.get("page").toString());
        Integer size = Integer.parseInt(params.get("limit").toString());
        QueryWrapper<AnswererEntity> wrapper =
                new QueryWrapper<AnswererEntity>();
        Page<AnswererEntity> page = new Page<AnswererEntity>(current, size);
        IPage<Map<String,Object>>mapIPage=null;
        wrapper.eq("a.is_deleted", 0);
        if (params.get("username") != null) {
            wrapper.like("a.username", params.get("username").toString().trim());
        }
        if (params.get("userId") != null) {
            if(!params.get("userId").equals("1")) {
                wrapper.eq("ua.user_id", params.get("userId"));
            }
            mapIPage = baseMapper.selectAnswerersUser(page, wrapper);
        }
        if(mapIPage==null){
            return new PageUtils(null,0,size,current);
        }
        List<Map<String, Object>> records = mapIPage.getRecords();
        PageUtils pageUtils = new PageUtils(records,(int)mapIPage.getTotal(),(int)mapIPage.getSize(),(int)mapIPage.getCurrent());
        return pageUtils;
    }


    //    操作用户答者关联表，删除对应记录
    @Transactional
    @Override
    public void removeAnswererInUser(Integer[] answererIds, int userId) {
        //TODO hsz:需要测试一下才知道是不是正确的逻辑
        for (int answererId : answererIds) {
            QueryWrapper<UserAnswererEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            wrapper.eq("answerer_id", answererId);
            answererService.delAnswerer(answererId);
            userAnswererService.remove(wrapper);
        }
//得到用户底下的所有答者群组
        QueryWrapper<UserTeamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<UserTeamEntity> list = userTeamService.list(wrapper);
        for (UserTeamEntity entity : list) {
            removeAnswererInTeam(answererIds, entity.getTeamId());
        }

    }

    @Autowired
    UserTeamService userTeamService;

    @Override
    public void removeAnswererInTeam(Integer[] answererIds, Integer teamId) {

//        删除群组底下的答者
        for (int answererId : answererIds) {
            QueryWrapper<AnswererTeamEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("team_id", teamId);
            wrapper.eq("answerer_id", answererId);
            answererTeamService.remove(wrapper);
        }
    }

    @Override
    public PageUtils notRelation(Map<String, Object> params) {
        //已经关联的答者列表
        QueryWrapper<AnswererTeamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("team_id", params.get("teamId"));
        List<AnswererTeamEntity> list = answererTeamService.list(wrapper);
        List<Integer> collect = list.stream().map(item -> {
            Integer answererId = item.getAnswererId();
            return answererId;
        }).collect(Collectors.toList());


        QueryWrapper<UserAnswererEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", params.get("userId"));
        List<UserAnswererEntity> list1 = userAnswererService.list(queryWrapper);


        List<Integer> noRelationIds = list1.stream().map(item -> {
            Integer answererId = item.getAnswererId();
            return answererId;
        }).filter(item -> {
            return !collect.contains(item);
        }).collect(Collectors.toList());
//        得到没关联此群组的答者id
        QueryWrapper<AnswererEntity> entityQueryWrapper = new QueryWrapper<>();
        if (noRelationIds.size() == 0) {
            entityQueryWrapper.eq("is_deleted", 3);
        } else {
            for (Integer noRelationId : noRelationIds) {
                entityQueryWrapper.or(item -> {
                    item.eq("id", noRelationId);
                });
            }
//            entityQueryWrapper.or(item -> {
//                for (Integer noRelationId : noRelationIds) {
//                    item.eq("id", noRelationId);
//                }
//            });
            entityQueryWrapper.and(item -> {
                item.eq("is_deleted", 0);
            });
        }

        IPage<AnswererEntity> page = this.page(
                new Query<AnswererEntity>().getPage(params),
                entityQueryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void associate(Map<String, Object> params) {
        AnswererTeamEntity answererTeamEntity = new AnswererTeamEntity();
        answererTeamEntity.setAnswererId(Integer.parseInt(params.get("answererId").toString()));
        answererTeamEntity.setTeamId(Integer.parseInt(params.get("teamId").toString()));
        answererTeamService.save(answererTeamEntity);
    }

    @Override
    public void removeAssociation(Map<String, Object> params) {
        QueryWrapper<AnswererTeamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("answerer_id", params.get("answererId"));
        wrapper.eq("team_id", params.get("teamId"));
        answererTeamService.remove(wrapper);
    }

    @Override
    public int addAnswererInfo(AnswererAddDto answererAddDto) {
        //获取传递过来的username
        String username = answererAddDto.getUsername();
        //获取传递过来的telephone
        String telephone = answererAddDto.getTelephone();
        //调用findByUsername(username)判断用户是否被注册过
        AnswererEntity result1 = answererDao.findByAnswerername(username);
        if (result1 != null) {
            return 0;
        }
        AnswererEntity result2 = answererService.findByTelephone(telephone);
        if (result2 != null) {
            return 2;
        }
        answererAddDto.setIsDeleted(0);
        int result = answererDao.insert(answererAddDto);
        return result;
    }

    @Override
    public AnswererEntity queryAnswererByDto(AnswererAddDto answererAddDto) {
        String username = answererAddDto.getUsername();
        String telephone = answererAddDto.getTelephone();
        AnswererEntity answererEntity = new AnswererEntity();
        answererEntity.setUsername(username);
        answererEntity.setTelephone(telephone);
        AnswererEntity answererEntity1 = answererDao.queryAnswererByDto(answererEntity);
        return answererEntity1;
    }



    @Transactional
    @Override
    public void saveAnswerersInUser(List<AnswererEntity> asList, int userId) {
//        先在Answerer_User关联表上关联关系写好
        List<UserAnswererEntity> collect = asList.stream().map(item -> {
            UserAnswererEntity entity = new UserAnswererEntity();
            entity.setUserId(item.getId());
            entity.setUserId(userId);
            return entity;
        }).collect(Collectors.toList());
        userAnswererService.saveBatch(collect);
//在Answerer表里加入相关信息 TODO 这里没考虑重复添加问题，下次迭代
        List<AnswererEntity> result = asList.stream().map(item -> {
//            修改Flag状态
            item.setFlag(1);
            return item;
        }).collect(Collectors.toList());
        this.saveBatch(result);
    }

    @Override
    public AnswererEntity login(AnswererEntity answererEntity) {
        QueryWrapper<AnswererEntity> queryWrapper = new QueryWrapper();
        if (answererEntity.getTelephone() != null) {
            String telephone = answererEntity.getTelephone();
            queryWrapper.eq("telephone", telephone);
        } else if (answererEntity.getUsername() != null) {
            String username = answererEntity.getUsername();
            queryWrapper.eq("username", username);
        }
        String password = answererEntity.getPassword();
        queryWrapper.eq("password", password);
        AnswererEntity one = this.getOne(queryWrapper);
        return one;
    }

    @Override
    public List<ResultEntity> queryResultList(@RequestParam Map<String, Object> params) {
        QueryWrapper<ResultEntity> wrapper =
                new QueryWrapper<ResultEntity>();
        if (params.get("answererId") != null) {
            wrapper.eq("answerer_id", params.get("answererId"));
        }
        if (params.get("questionnaireName") != null) {
            wrapper.like("questionnaire_name", params.get("questionnaireName"));
        }
        List<ResultEntity> list = resultService.list(wrapper);
        return list;
    }

    @Override
    public AnswererEntity findByAnswerername(String username) {
        AnswererEntity result = answererDao.findByAnswerername(username);
        return result;
    }

    @Override
    public AnswererEntity findByAnswererId(int id) {
        AnswererEntity answererEntity = answererDao.findByAnswererId(id);
        return answererEntity;
    }

    @Override
    public void modifyAnswererInfo(AnswererEntity answererEntity) {
        answererDao.modifyAnswererInfo(answererEntity);
    }

    @Override
    public void delAnswerer(int id) {
        answererDao.delAnswerer(id);
    }

    @Override
    public List<ResultEntity> analysis(Integer questionnaireId) {
        QueryWrapper<ResultEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("questionnaire_id", questionnaireId);
        wrapper.eq("is_finish", 1);
        List<ResultEntity> list = resultService.list(wrapper);
        return list;
    }

    @Override
    public AnswererEntity findByTelephone(String telephone) {
        AnswererEntity result = answererDao.findByTelephone(telephone);
        return result;
    }

    /*
答者注册
 */
    @Override
    public int reg(AnswererEntity answererEntity) {
        //获取传递过来的username
        String username = answererEntity.getUsername();
        //获取传递过来的telephone
        String telephone = answererEntity.getTelephone();
        //调用findByUsername(username)判断用户是否被注册过
        AnswererEntity result1 = answererDao.findByAnswerername(username);
        if (result1 != null) {
            return 0;
        }
        AnswererEntity result2 = answererService.findByTelephone(telephone);
        if (result2 != null) {
            return 0;
        }
//        // 获取原始密码
//        String oldpassword = user.getPassword();
//        // 调用md5算法获取加密密码
//        String md5Password = getMD5Password(oldpassword);
//        // 将加密后的密码重新补全设置到user中
//        user.setPassword(md5Password);
        answererEntity.setIsDeleted(0);
        int rows = answererDao.insert(answererEntity);
        return rows;
    }

    @Override
    public PageUtils teamanswerers( Map<String, Object> params) {
        Integer current = Integer.parseInt(params.get("page").toString());
        Integer size = Integer.parseInt(params.get("limit").toString());
        QueryWrapper<AnswererEntity> wrapper =
                new QueryWrapper<AnswererEntity>();
        Page<AnswererEntity> page = new Page<AnswererEntity>(current, size);
        IPage<Map<String,Object>>mapIPage=null;
        wrapper.eq("a.is_deleted", 0);
        if (params.get("username") != null) {
            wrapper.like("a.username", params.get("username").toString().trim().length());
        }
        if (params.get("teamId") != null) {
            wrapper.eq("ant.team_id", params.get("teamId"));
            mapIPage= baseMapper.selectAnswerersTeam( page, wrapper);
        }
        if(mapIPage==null){
            return new PageUtils(null,0,size,current);
        }
        List<Map<String, Object>> records = mapIPage.getRecords();
        PageUtils pageUtils = new PageUtils(records,(int)mapIPage.getTotal(),(int)mapIPage.getSize(),(int)mapIPage.getCurrent());
        return pageUtils;
    }

    @Override
    public List<Integer> findQuestionnaireIdByAnswererId(Integer answererId) {

        List<Integer> QuestionnaireIdList = answererDao.findQuestionnaireIdByAnswererId(answererId);
        return QuestionnaireIdList;
    }

    @Override
    public List<QuestionnaireEntity> findQuestionnaireByKeyWord(List<Integer> questionnaireIdList, String keyword) {
        List<QuestionnaireEntity> list = answererDao.findQuestionnaireByKeyWord(questionnaireIdList, keyword);
        return list;
    }


    @Override
    public void addAnswererTeamInfo(AnswererAddDto answererAddDto) {
        if(answererAddDto.getTeamId()!=0) {
            answererDao.addAnswererTeamInfo(answererAddDto);
        }
    }

    @Override
    public AnswererEntity login(String username, String password) {
        AnswererEntity result = answererDao.login(username,password);
        return result;
    }
}